import React, { useEffect, useState } from 'react'
import {
    Table, Pagination, Spin, Alert,
    Form,
    Input,
    Button,
    Row,
    Col,
    Space,
    Typography, Select, Empty
} from 'antd';
import backgroundImage from '../images/form_bg@2x.2d429e6ecd7d2c432e6f.png';
import {request} from "../utils/requset";
import { useSelector } from "react-redux";
const { Option } =  Select; 


const backgroundStyle = {
    backgroundImage: `url(${backgroundImage})`,
    backgroundSize: 'cover', // 使背景图片覆盖整个容器
    backgroundPosition: 'center', // 背景图片居中
    backgroundRepeat: 'no-repeat', // 防止背景图片重复
    // minHeight: '100vh', // 确保背景图片覆盖整个视口高度
    // 其他您需要的样式
};


const { Title } = Typography;

const NwBmzdPage = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [runLoading, setRunLoading] = useState(false);
    const [error, setError] = useState(false);
    const [pageNum, setPageNum] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [dataSource, setDataSource] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 选中行的状态
    const [tableHeight, setTableHeight] = useState(500); // 默认高度
    const [typeList, setTypeList] = useState([]);
    const [tjList, setTjList] = useState([]);

    const sysConfig = useSelector(state => state.pz.sysConfig);


    const [searchParams, setSearchParams] = useState({});

    // 在组件挂载时获取数据
    useEffect(() => {
        fetchData(pageNum, pageSize);
    }, [sysConfig, pageNum, pageSize, searchParams]);

    useEffect(() => {
        fetchTypeList();
        fetchTjList();
    }, [sysConfig]);

    // 获取表格数据的函数
    const fetchData = async (currentPage = 1, size = 10) => {
        setRunLoading(true);
        setError(null);
        try {
            const response = await request.post('/rpa/dict/search', {
                "table": 't_api_bm',
                "page": currentPage,
                "pageSize": size,
                "filters": searchParams
            }
            );

            const jsonData = response.data;
            setPageNum(currentPage);
            setPageSize(size);
            setTotal(jsonData.total);
            setDataSource(jsonData.data);
        } catch (err) {
            // console.error('数据获取失败:', err);
            setError('数据获取失败，请稍后再试。');
        } finally {
            setRunLoading(false);
        }
    };

    const fetchTypeList = async () => {
        setRunLoading(true);
        setError(null);
        try {
            const response = await request.get('/rpa/bmzd/fiyearlist');
            const jsonData = response.data;
            setTypeList(jsonData.list);
            console.log(jsonData.list);
        } catch (err) {
            // console.error('数据获取失败:', err);
            setError('数据获取失败，请稍后再试。');
        } finally {
            setRunLoading(false);
        }
    };
    const fetchTjList = async () => {
        setRunLoading(true);
        setError(null);
        try {
            const response = await request.get('/rpa/bmzd/drsjlist');
            const jsonData = response.data;
            setTjList(jsonData.list);
            console.log(jsonData.list);
        } catch (err) {
            // console.error('数据获取失败:', err);
            setError('数据获取失败，请稍后再试。');
        } finally {
            setRunLoading(false);
        }
    };

    // 动态设置表格高度
    useEffect(() => {
        const updateTableHeight = () => {
            const viewportHeight = window.innerHeight;
            const desiredHeight = viewportHeight / 2 - 50; // 例如，减去200像素用于其他内容
            setTableHeight(desiredHeight > 300 ? desiredHeight : 300); // 设置最小高度为300
        };

        updateTableHeight();
        window.addEventListener('resize', updateTableHeight);
        return () => window.removeEventListener('resize', updateTableHeight);
    }, []);

    const NwPzColumns = [
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
            width: 100,
        },
        {
            title: '部门编号',
            dataIndex: 'code',
            key: 'code',
            width: 100,
        },
        {
            title: '部门名称',
            dataIndex: 'name_chs',
            key: 'name_chs',
            width: 100,
        },
        {
            title: '部门全称',
            dataIndex: 'fullname_chs',
            key: 'fullname_chs',
            width: 100,
        },
        {
            title: '核算组织ID',
            dataIndex: 'accorgid',
            key: 'accorgid',
            width: 100,
        },
        {
            title: '核算组织编号',
            dataIndex: 'orgcode',
            key: 'orgcode',
            width: 100,
        },
        {
            title: '核算组织名称',
            dataIndex: 'orgname',
            key: 'orgname',
            width: 100,
        },
        {
            title: '对应组织结构内码',
            dataIndex: 'admindeptid',
            key: 'admindeptid',
            width: 100,
        },
        {
            title: '明细否',
            dataIndex: 'treeinfo_isdetail',
            key: 'treeinfo_isdetail',
            width: 100,
            render: (text) => text == "1" ? "是" : "否",
        },
        {
            title: '级数',
            dataIndex: 'treeinfo_layer',
            key: 'treeinfo_layer',
            width: 100,
        },
        {
            title: '分级码',
            dataIndex: 'treeinfo_path',
            key: 'treeinfo_path',
            width: 100,
        },
        {
            title: '父节点ID',
            dataIndex: 'parentid',
            key: 'parentid',
            width: 100,
        },
        {
            title: '停用否',
            dataIndex: 'isdisable',
            key: 'isdisable',
            width: 100,
            render: (text) => text == "1" ? "是" : "否",
        },
        {
            title: '停用年度',
            dataIndex: 'disableyear',
            key: 'disableyear',
            width: 100,
        },
        {
            title: '兄弟节点排序号',
            dataIndex: 'sortorder',
            key: 'sortorder',
            width: 100,
        },
        {
            title: '会计年度',
            dataIndex: 'fiyear',
            key: 'fiyear',
            width: 100,
        },
        {
            title: '创建时间',
            dataIndex: 'timestamp_createdon',
            key: 'timestamp_createdon',
            width: 100,
        },
        {
            title: '最后更新时间',
            dataIndex: 'timestamp_lastchangedon',
            key: 'timestamp_lastchangedon',
            width: 100,
        },
        {
            title: '导入时间',
            dataIndex: 'esun_api_update',
            key: 'esun_api_update',
            width: 100,
        },
        
    ];
    

    const handleGetData = async () => {

        const values = await form.validateFields();

        setPageNum(1);
        setPageSize(10);
        setSearchParams({
            ...searchParams,
            ...values
        });
    }


    // 计算当前页显示的条数
    const startRow = (pageNum - 1) * pageSize + 1;
    const endRow = Math.min(pageNum * pageSize, total);
    // 页码变化时
    const onPageChange = (page, size) => {
        // console.log(page, size)
        setPageNum(page); // 设置当前页
        setPageSize(size); // 设置每页条数
    };

    const handleClearCondition = () => {
        setPageNum(1);
        setPageSize(10);
        setSearchParams({});
        form.resetFields()
    };

    return (
        <>
            <Row justify="center">
                <Col xs={24} sm={20} md={24}>
                    <div className="config-page-layout float-center" style={backgroundStyle}>
                        <div className="upper-section">
                            <Title>
                                部门字典查询
                                {/* 保存和运行按钮 */}
                                <Space className='float-right' style={{ marginBottom: 16, marginLeft: 8 }}>
                                    <Button type="primary" onClick={handleGetData} loading={runLoading}
                                        className='float-right'>
                                        查询
                                    </Button>
                                    <Button onClick={handleClearCondition} loading={runLoading}
                                        className='float-right'>
                                        清除条件
                                    </Button>
                                </Space>
                            </Title>

                            <Form
                                form={form}
                                layout="vertical"
                            >
                                <Row gutter={16}>
                                    <Col xs={24} sm={6} md={9}>

                                        <Form.Item
                                            label="部门名称"
                                            name="name_chs"
                                        >
                                            <Input
                                                placeholder="部门名称"
                                                value={searchParams.name_chs}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={6}>
                                        <Form.Item
                                            label="部门编号"
                                            name="code"
                                        >
                                            <Input
                                                placeholder="部门编号"
                                                value={searchParams.code}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={3}>
                                        <Form.Item
                                            label="会计年度"
                                            name="fiyear"
                                        >
                                            <Select placeholder="请选择年度" allowClear>
                                              {typeList.map((mode) => (
                                                <Option key={mode} value={mode}>
                                                  {mode}
                                                </Option>
                                              ))}
                                            </Select>
                                        </Form.Item>
                                    </Col>
                                    <Col xs={24} sm={6} md={3}>
                                        <Form.Item
                                            label="导入时间"
                                            name="esun_api_update"
                                        >
                                            <Select placeholder="请选择导入时间" allowClear>
                                              {tjList.map((mode) => (
                                                <Option key={mode} value={mode}>
                                                  {mode}
                                                </Option>
                                              ))}
                                            </Select>
                                        </Form.Item>
                                    </Col>
                                </Row>

                            </Form>
                        </div>

                        {/* 下部分的表格 */}
                        <div className="lower-section">
                            <div className="my-data-table-container">
                                {error && <Alert message={error} type="error" showIcon style={{ marginBottom: 16 }} />}

                                <Spin spinning={loading}>
                                    <Table
                                        size="small"
                                        columns={NwPzColumns}
                                        dataSource={dataSource}
                                        rowKey="uuid"
                                        pagination={false} // 使用自定义的分页组件
                                        scroll={{ x: 'max-content', y: tableHeight }} // 启用水平和垂直滚动
                                        rowClassName={(record) =>
                                            selectedRowKeys.includes(record.uuid) ? 'selected-row' : ''
                                        }
                                        locale={{ emptyText: <Empty description="未查询到数据"></Empty> }} // 自定义无数据时显示的文字
                                    />
                                </Spin>
                                <div>
                                    <span>
                                        当前 {startRow}-{endRow} 条，共 {total} 条
                                    </span>
                                    <Pagination
                                        current={pageNum}
                                        pageSize={pageSize}
                                        total={total}
                                        showSizeChanger
                                        pageSizeOptions={['10', '20', '50', '100']} // 限制每页条目数选项
                                        style={{ marginTop: 16, textAlign: 'right' }}
                                        onChange={onPageChange}      // 页码变化时触发
                                    />
                                </div>
                            </div>
                        </div>
                    </div>
                </Col>
            </Row>
        </>
    )
}

export default NwBmzdPage